#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    label = new QLabel;

    ui->statusBar->addWidget(label);

    highlighter = new Highlighter(ui->plainTextEdit->document());

    connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(textChange(QString)));
    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(testButton()));
    connect(this->highlighter, SIGNAL(status(int,int)), this, SLOT(updateStatus(int,int)));
    connect(ui->plainTextEdit, SIGNAL(textChanged()), this , SLOT(testButton()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::textChange(QString text)
{
    testButton();
}

void MainWindow::testButton()
{
    if (ui->lineEdit->text().isEmpty())
    {
        return;
    }

#if 1
    pcre *pc;
    const char *err;
    int offset;

    pc = pcre_compile(ui->lineEdit->text().toStdString().c_str(), 0, &err, &offset, NULL);
    if (pc == NULL)
    {
        ui->lineEdit->setStyleSheet("color:red");
        label->setStyleSheet("color:red");
        label->setText("Error: " + QString(err) + ". Pos: " + QString::number(offset));
        return;
    }

    ui->lineEdit->setStyleSheet("color:green");
    label->setStyleSheet("color:green");
    label->setText("");
    pcre_free(pc);
#else
    QRegExp rx(ui->lineEdit->text());
    if (!rx.isValid())
    {
        ui->lineEdit->setStyleSheet("color:red");
        label->setStyleSheet("color:red");
        label->setText(rx.errorString());
        return;
    }
    else
    {
        ui->lineEdit->setStyleSheet("color:green");
        label->setStyleSheet("color:green");
        label->setText("");
    }
#endif

    if (ui->checkBox->checkState() == Qt::Checked)
    {
        this->highlighter->ruleChange(ui->lineEdit->text());
    }
}

void MainWindow::updateStatus(int result, int size)
{
    if (!result)
    {
        label->setText("Test failed.");
    }else
    {
        label->setText("Test succed. Total match " + QString::number(size));
    }
}
